#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include <GLFW/glfw3.h>
#include <vector>
#include <cmath>
#include <algorithm>
#include <string>

// 图像数据结构
struct ImageData {
    float* pixels;
    int width;
    int height;
    int channels;

    ImageData(int w, int h, int c) : width(w), height(h), channels(c) {
        pixels = new float[w * h * c];
        // 初始化像素数据
        for (int i = 0; i < w * h * c; i++) {
            pixels[i] = 0.5f; // 默认灰色
        }
    }

    ~ImageData() {
        delete[] pixels;
    }
};

// 应用程序状态
struct AppState {
    // 图像处理
    ImageData* currentImage;
    float brightness = 1.0f;
    float contrast = 1.0f;
    float saturation = 1.0f;
    bool invertColors = false;

    // 3D场景
    float rotation[3] = {0.0f, 0.0f, 0.0f};
    float scale = 1.0f;
    bool showWireframe = false;

    // 数据可视化
    std::vector<float> dataPoints;
    int selectedGraphType = 0;

    // UI状态
    bool showDemoWindow = false;
    bool showImageEditor = true;
    bool show3DViewer = true;
    bool showDataVisualization = true;
    bool showSettings = false;

    AppState() {
        currentImage = new ImageData(256, 256, 3);

        // 生成示例数据点
        for (int i = 0; i < 100; i++) {
            dataPoints.push_back(sin(i * 0.1f) + cos(i * 0.05f));
        }
    }

    ~AppState() {
        delete currentImage;
    }
};

// 图像处理函数
void ApplyImageFilters(ImageData* image, float brightness, float contrast, float saturation, bool invert) {
    // 在实际应用中，这里会实现实际的图像处理算法
    // 这里只是模拟处理过程
}

// 生成示例纹理ID（在实际应用中，这里会使用OpenGL纹理）
void* GenerateExampleTexture() {
    // 返回一个模拟的纹理ID
    static int dummyTextureId = 1;
    return reinterpret_cast<void*>(static_cast<intptr_t>(dummyTextureId));
}

// 绘制3D场景（简化版）
void Draw3DScene(float rotation[3], float scale, bool wireframe) {
    // 在实际应用中，这里会使用OpenGL绘制3D场景
    // 这里只是绘制一个简单的立方体表示
    ImGui::Text("3D场景预览 (模拟)");
    ImGui::Text("旋转: %.1f, %.1f, %.1f", rotation[0], rotation[1], rotation[2]);
    ImGui::Text("缩放: %.1f", scale);
    ImGui::Text("模式: %s", wireframe ? "线框" : "实体");

    // 绘制一个简单的立方体表示
    ImDrawList* draw_list = ImGui::GetWindowDrawList();
    ImVec2 canvas_pos = ImGui::GetCursorScreenPos();
    ImVec2 canvas_size = ImGui::GetContentRegionAvail();

    // 绘制一个简单的立方体轮廓
    float cube_size = std::min(canvas_size.x, canvas_size.y) * 0.5f * scale;
    ImVec2 center(canvas_pos.x + canvas_size.x * 0.5f, canvas_pos.y + canvas_size.y * 0.5f);

    // 立方体顶点（简化表示）
    ImVec2 front_vertices[4] = {
            ImVec2(center.x - cube_size, center.y - cube_size),
            ImVec2(center.x + cube_size, center.y - cube_size),
            ImVec2(center.x + cube_size, center.y + cube_size),
            ImVec2(center.x - cube_size, center.y + cube_size)
    };

    // 绘制立方体
    if (wireframe) {
        draw_list->AddPolyline(front_vertices, 4, IM_COL32(255, 255, 255, 255), true, 2.0f);
    } else {
        draw_list->AddQuadFilled(
                front_vertices[0], front_vertices[1], front_vertices[2], front_vertices[3],
                IM_COL32(100, 150, 200, 255)
        );
    }

    ImGui::Dummy(canvas_size);
}

// 绘制数据可视化图表
void DrawDataVisualization(const std::vector<float>& data, int graphType) {
    ImVec2 canvas_size = ImGui::GetContentRegionAvail();
    ImDrawList* draw_list = ImGui::GetWindowDrawList();
    ImVec2 canvas_pos = ImGui::GetCursorScreenPos();

    if (data.empty()) return;

    // 绘制图表背景
    draw_list->AddRectFilled(
            canvas_pos,
            ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y),
            IM_COL32(30, 30, 30, 255)
    );

    // 绘制网格
    float grid_spacing_x = canvas_size.x / 10.0f;
    float grid_spacing_y = canvas_size.y / 10.0f;

    for (int i = 1; i < 10; i++) {
        draw_list->AddLine(
                ImVec2(canvas_pos.x + i * grid_spacing_x, canvas_pos.y),
                ImVec2(canvas_pos.x + i * grid_spacing_x, canvas_pos.y + canvas_size.y),
                IM_COL32(60, 60, 60, 255)
        );
    }

    for (int i = 1; i < 10; i++) {
        draw_list->AddLine(
                ImVec2(canvas_pos.x, canvas_pos.y + i * grid_spacing_y),
                ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + i * grid_spacing_y),
                IM_COL32(60, 60, 60, 255)
        );
    }

    // 绘制数据
    float max_val = *std::max_element(data.begin(), data.end());
    float min_val = *std::min_element(data.begin(), data.end());
    float range = max_val - min_val;
    if (range == 0) range = 1.0f;

    ImVec2 prev_point;
    for (size_t i = 0; i < data.size(); i++) {
        float x = canvas_pos.x + (i / (float)(data.size() - 1)) * canvas_size.x;
        float normalized_val = (data[i] - min_val) / range;
        float y = canvas_pos.y + canvas_size.y - normalized_val * canvas_size.y;

        ImVec2 current_point(x, y);

        if (graphType == 0) { // 折线图
            if (i > 0) {
                draw_list->AddLine(prev_point, current_point, IM_COL32(0, 255, 100, 255), 2.0f);
            }
            draw_list->AddCircleFilled(current_point, 3.0f, IM_COL32(255, 255, 255, 255));
        } else if (graphType == 1) { // 柱状图
            float bar_width = canvas_size.x / data.size();
            draw_list->AddRectFilled(
                    ImVec2(x - bar_width/2, y),
                    ImVec2(x + bar_width/2, canvas_pos.y + canvas_size.y),
                    IM_COL32(100, 150, 255, 255)
            );
        }

        prev_point = current_point;
    }

    ImGui::Dummy(canvas_size);
}

// 主UI渲染函数
void RenderUI(AppState& state) {
    // 主菜单栏
    if (ImGui::BeginMainMenuBar()) {
        if (ImGui::BeginMenu("文件")) {
            if (ImGui::MenuItem("新建")) {}
            if (ImGui::MenuItem("打开", "Ctrl+O")) {}
            if (ImGui::MenuItem("保存", "Ctrl+S")) {}
            ImGui::Separator();
            if (ImGui::MenuItem("退出", "Alt+F4")) {}
            ImGui::EndMenu();
        }
        if (ImGui::BeginMenu("视图")) {
            ImGui::MenuItem("图像编辑器", NULL, &state.showImageEditor);
            ImGui::MenuItem("3D查看器", NULL, &state.show3DViewer);
            ImGui::MenuItem("数据可视化", NULL, &state.showDataVisualization);
            ImGui::MenuItem("设置", NULL, &state.showSettings);
            ImGui::Separator();
            ImGui::MenuItem("ImGui演示窗口", NULL, &state.showDemoWindow);
            ImGui::EndMenu();
        }
        if (ImGui::BeginMenu("帮助")) {
            if (ImGui::MenuItem("关于")) {}
            ImGui::EndMenu();
        }
        ImGui::EndMainMenuBar();
    }

    // 主控制面板
    ImGui::Begin("控制面板");

    ImGui::Text("应用程序状态");
    ImGui::Separator();

    // 性能指标
    ImGui::Text("平均 %.3f ms/帧 (%.1f FPS)",
                1000.0f / ImGui::GetIO().Framerate,
                ImGui::GetIO().Framerate);

    ImGui::Spacing();
    ImGui::Separator();
    ImGui::Spacing();

    // 模块控制
    ImGui::Text("模块控制:");
    ImGui::Checkbox("图像编辑器", &state.showImageEditor);
    ImGui::Checkbox("3D查看器", &state.show3DViewer);
    ImGui::Checkbox("数据可视化", &state.showDataVisualization);
    ImGui::Checkbox("设置面板", &state.showSettings);

    ImGui::End();

    // 图像编辑器窗口
    if (state.showImageEditor) {
        ImGui::Begin("图像编辑器", &state.showImageEditor);

        // 图像预览
        ImGui::Text("图像预览");
        ImVec2 image_size(256, 256);
        ImGui::Image(GenerateExampleTexture(), image_size);

        // 图像处理控件
        ImGui::Separator();
        ImGui::Text("图像调整");

        ImGui::SliderFloat("亮度", &state.brightness, 0.0f, 2.0f);
        ImGui::SliderFloat("对比度", &state.contrast, 0.0f, 2.0f);
        ImGui::SliderFloat("饱和度", &state.saturation, 0.0f, 2.0f);
        ImGui::Checkbox("反色", &state.invertColors);

        // 应用按钮
        if (ImGui::Button("应用滤镜")) {
            ApplyImageFilters(state.currentImage,
                              state.brightness,
                              state.contrast,
                              state.saturation,
                              state.invertColors);
        }

        ImGui::SameLine();
        if (ImGui::Button("重置")) {
            state.brightness = 1.0f;
            state.contrast = 1.0f;
            state.saturation = 1.0f;
            state.invertColors = false;
        }

        ImGui::End();
    }

    // 3D查看器窗口
    if (state.show3DViewer) {
        ImGui::Begin("3D查看器", &state.show3DViewer);

        // 3D场景控制
        ImGui::Text("3D场景控制");
        ImGui::SliderFloat3("旋转", state.rotation, -180.0f, 180.0f);
        ImGui::SliderFloat("缩放", &state.scale, 0.1f, 3.0f);
        ImGui::Checkbox("线框模式", &state.showWireframe);

        ImGui::Separator();
        ImGui::Text("3D场景");

        // 绘制3D场景
        Draw3DScene(state.rotation, state.scale, state.showWireframe);

        ImGui::End();
    }

    // 数据可视化窗口
    if (state.showDataVisualization) {
        ImGui::Begin("数据可视化", &state.showDataVisualization);

        // 图表类型选择
        ImGui::Text("图表类型");
        const char* graph_types[] = {"折线图", "柱状图"};
        ImGui::Combo("类型", &state.selectedGraphType, graph_types, IM_ARRAYSIZE(graph_types));

        // 数据控制
        ImGui::SameLine();
        if (ImGui::Button("生成新数据")) {
            state.dataPoints.clear();
            for (int i = 0; i < 100; i++) {
                state.dataPoints.push_back(sin(i * 0.1f + ImGui::GetTime()) +
                                           cos(i * 0.05f + ImGui::GetTime()));
            }
        }

        ImGui::Separator();
        ImGui::Text("数据图表");

        // 绘制数据可视化
        DrawDataVisualization(state.dataPoints, state.selectedGraphType);

        ImGui::End();
    }

    // 设置窗口
    if (state.showSettings) {
        ImGui::Begin("设置", &state.showSettings);

        ImGui::Text("应用程序设置");
        ImGui::Separator();

        // 主题选择
        static int theme = 0;
        const char* themes[] = {"深色", "浅色", "经典"};
        if (ImGui::Combo("主题", &theme, themes, IM_ARRAYSIZE(themes))) {
            switch (theme) {
                case 0: ImGui::StyleColorsDark(); break;
                case 1: ImGui::StyleColorsLight(); break;
                case 2: ImGui::StyleColorsClassic(); break;
            }
        }

        // UI缩放
        static float ui_scale = 1.0f;
        if (ImGui::SliderFloat("UI缩放", &ui_scale, 0.5f, 2.0f)) {
            ImGui::GetIO().FontGlobalScale = ui_scale;
        }

        ImGui::Separator();
        ImGui::Text("其他设置");

        // 其他设置选项
        static bool auto_save = false;
        ImGui::Checkbox("自动保存", &auto_save);

        static int language = 0;
        const char* languages[] = {"English", "中文", "Español"};
        ImGui::Combo("语言", &language, languages, IM_ARRAYSIZE(languages));

        ImGui::End();
    }

    // ImGui演示窗口（可选）
    if (state.showDemoWindow) {
        ImGui::ShowDemoWindow(&state.showDemoWindow);
    }
}

// 主函数
int main() {
    // 初始化GLFW
    if (!glfwInit()) {
        return -1;
    }

    // 创建窗口
    GLFWwindow* window = glfwCreateWindow(1400, 900, "ImGui多功能应用程序", NULL, NULL);
    if (!window) {
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSwapInterval(1); // 启用垂直同步

    // 初始化ImGui
    IMGUI_CHECKVERSION();
    ImGui::CreateContext();
    ImGuiIO& io = ImGui::GetIO(); (void)io;
    ImFontConfig font_cfg;
    font_cfg.FontNo = 0; // 尝试加载ttc文件的第一个字体
    io.Fonts->AddFontFromFileTTF("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", 20.0f, &font_cfg, io.Fonts->GetGlyphRangesChineseFull());

    // 设置ImGui样式
    ImGui::StyleColorsDark();

    // 初始化平台/渲染器后端
    ImGui_ImplGlfw_InitForOpenGL(window, true);
    ImGui_ImplOpenGL3_Init("#version 130");

    // 应用程序状态
    AppState appState;

    // 主循环
    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();

        // 开始新帧
        ImGui_ImplOpenGL3_NewFrame();
        ImGui_ImplGlfw_NewFrame();
        ImGui::NewFrame();

        // 渲染UI
        RenderUI(appState);

        // 渲染
        ImGui::Render();
        int display_w, display_h;
        glfwGetFramebufferSize(window, &display_w, &display_h);
        glViewport(0, 0, display_w, display_h);
        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());

        glfwSwapBuffers(window);
    }

    // 清理
    ImGui_ImplOpenGL3_Shutdown();
    ImGui_ImplGlfw_Shutdown();
    ImGui::DestroyContext();

    glfwDestroyWindow(window);
    glfwTerminate();

    return 0;
}